// ============================================================================
// 创建定时任务模态框组件
// ============================================================================

import React, { useState } from 'react'
import { schedulerService, CreateScheduledTaskOptions } from '../services/scheduler-service'
import { WeiboLoginData } from '../../shared/types'
import { useNotifications } from '../hooks/use-notifications'
import { logger } from '../utils/logger'

interface CreateTaskModalProps {
  accounts: WeiboLoginData[]
  onClose: () => void
  onSuccess: () => void
}

/**
 * 创建定时任务模态框组件
 */
export const CreateTaskModal: React.FC<CreateTaskModalProps> = ({
  accounts,
  onClose,
  onSuccess
}) => {
  const [formData, setFormData] = useState({
    keywords: '',
    accountId: '',
    interval: '30', // 分钟
    maxPages: '3',
    count: '50',
    enabled: true
  })
  const [loading, setLoading] = useState(false)
  const { showSuccess, showError } = useNotifications()

  /**
   * 处理表单提交
   */
  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault()
    
    if (loading) return

    try {
      setLoading(true)

      // 验证表单
      if (!formData.keywords.trim()) {
        showError('请输入关键字', '')
        return
      }

      if (!formData.accountId) {
        showError('请选择账号', '')
        return
      }

      // 解析关键字
      const keywords = formData.keywords
        .split(/[,，\n]/)
        .map(k => k.trim())
        .filter(k => k.length > 0)

      if (keywords.length === 0) {
        showError('请输入有效的关键字', '')
        return
      }

      // 构建选项
      const options: CreateScheduledTaskOptions = {
        interval: parseInt(formData.interval) * 60 * 1000, // 转换为毫秒
        maxPages: parseInt(formData.maxPages),
        count: parseInt(formData.count),
        enabled: formData.enabled
      }

      // 创建任务
      await schedulerService.createScheduledTask(
        keywords,
        formData.accountId,
        options
      )

      showSuccess('定时任务创建成功', '')
      onSuccess()

    } catch (error) {
      logger.error('创建定时任务失败', error)
      showError(
        error instanceof Error ? error.message : '创建任务失败',
        ''
      )
    } finally {
      setLoading(false)
    }
  }

  /**
   * 处理输入变化
   */
  const handleInputChange = (
    field: string,
    value: string | boolean | number
  ) => {
    setFormData(prev => ({
      ...prev,
      [field]: value
    }))
  }

  return (
    <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50">
      <div className="bg-white rounded-lg shadow-xl w-full max-w-2xl mx-4 max-h-[90vh] overflow-y-auto">
        <div className="px-6 py-4 border-b">
          <h2 className="text-xl font-semibold text-gray-900">创建定时任务</h2>
        </div>

        <form onSubmit={handleSubmit} className="p-6 space-y-6">
          {/* 关键字输入 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              关键字 *
            </label>
            <textarea
              value={formData.keywords}
              onChange={(e) => handleInputChange('keywords', e.target.value)}
              placeholder="请输入关键字，多个关键字用逗号或换行分隔"
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              rows={3}
              required
            />
            <p className="text-xs text-gray-500 mt-1">
              支持多个关键字，用逗号、中文逗号或换行分隔
            </p>
          </div>

          {/* 账号选择 */}
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-2">
              使用账号 *
            </label>
            <select
              value={formData.accountId}
              onChange={(e) => handleInputChange('accountId', e.target.value)}
              className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
              required
            >
              <option value="">请选择账号</option>
              {accounts.map((account) => (
                <option key={account.id} value={account.id}>
                  {account.userInfo.screen_name} ({account.userInfo.id})
                </option>
              ))}
            </select>
          </div>

          {/* 执行间隔 */}
          <div className="grid grid-cols-1 md:grid-cols-1 gap-4">
            <div>
              <label className="block text-sm font-medium text-gray-700 mb-2">
                执行间隔（分钟）*
              </label>
              <input
                type="number"
                value={formData.interval}
                onChange={(e) => handleInputChange('interval', e.target.value)}
                min="1"
                max="1440"
                className="w-full px-3 py-2 border border-gray-300 rounded-lg focus:ring-2 focus:ring-blue-500 focus:border-blue-500"
                required
              />
              <p className="text-xs text-gray-500 mt-1">
                最小1分钟，最大24小时（1440分钟）
              </p>
            </div>
          </div>

          {/* 选项 */}
          <div className="space-y-3">
            <label className="block text-sm font-medium text-gray-700">
              任务选项
            </label>

            <div className="space-y-2">
              <label className="flex items-center">
                <input
                  type="checkbox"
                  checked={formData.enabled}
                  onChange={(e) => handleInputChange('enabled', e.target.checked)}
                  className="rounded border-gray-300 text-blue-600 focus:ring-blue-500"
                />
                <span className="ml-2 text-sm text-gray-700">创建后立即启用</span>
              </label>
            </div>
          </div>

          {/* 按钮 */}
          <div className="flex justify-end space-x-3 pt-4 border-t">
            <button
              type="button"
              onClick={onClose}
              className="px-4 py-2 text-gray-700 bg-gray-100 rounded-lg hover:bg-gray-200"
              disabled={loading}
            >
              取消
            </button>
            <button
              type="submit"
              className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50"
              disabled={loading}
            >
              {loading ? '创建中...' : '创建任务'}
            </button>
          </div>
        </form>
      </div>
    </div>
  )
}
